package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.cart.client.FeignCartClient;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: lx
 * @Time: 10:14
 * @Description:
 *
 *   结算
 *
 *
 */
@Controller
public class TradeController {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private FeignCartClient feignCartClient;
    @Autowired
    private OrderFeignClient orderFeignClient;
    //结算
    @GetMapping("/trade.html")
    public String trade(Model model){
        //1:收货人地址集合  根据用户ID  用户微服务
        List<UserAddress> userAddressList = userFeignClient.findUserAddressList();
        model.addAttribute("userAddressList",userAddressList);
        //2:订单号 （交易号） （防止重复提交）   幂等性问题
        String tradeNo = orderFeignClient.getTradeNo();
        model.addAttribute("tradeNo",tradeNo);
        //3:商品清单
        List<CartInfo> cartCheckedList = feignCartClient.getCartCheckedList();
        List<OrderDetail> orderDetailList = cartCheckedList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            return orderDetail;
        }).collect(Collectors.toList());
        model.addAttribute("detailArrayList",orderDetailList);
        //4:总件数
        long sum = cartCheckedList.stream()
                .collect(Collectors.summarizingInt(CartInfo::getSkuNum)).getSum();
        model.addAttribute("totalNum",sum);
        //5:总金额
        BigDecimal totalAmount = new BigDecimal("0");
        for (CartInfo cartInfo : cartCheckedList) {
            totalAmount = totalAmount.add(cartInfo.getSkuPrice().multiply(new BigDecimal(cartInfo.getSkuNum())));
        }
        model.addAttribute("totalAmount",totalAmount);
        return "order/trade";
    }
}
